package cn.bossfriday.im.api.actor;

import cn.bossfriday.common.register.ActorRoute;
import cn.bossfriday.common.rpc.actor.BaseUntypedActor;
import cn.bossfriday.im.common.api.ApiResponseHelper;
import cn.bossfriday.im.common.conf.ConfigurationAllLoader;
import cn.bossfriday.im.common.entity.result.Result;
import cn.bossfriday.im.common.message.api.enties.AccessServerAddress;
import cn.bossfriday.im.common.message.api.user.NavigateResponse;
import cn.bossfriday.im.common.message.rpc.access.GetAccessAddressOutput;
import cn.bossfriday.im.common.poc.model.enums.ConnectType;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

import static cn.bossfriday.im.common.constant.ImConstant.ACTOR_API_GET_ACCESS_ADDRESS_ACK;
import static cn.bossfriday.im.common.entity.result.ResultCode.API_UNSUPPORTED_API_ACK_MESSAGE_TYPE;
import static cn.bossfriday.im.common.entity.result.ResultCode.SYSTEM_ERROR;

/**
 * GetAccessAddressAckActor
 *
 * @author chenx
 */
@Slf4j
@ActorRoute(methods = ACTOR_API_GET_ACCESS_ADDRESS_ACK)
public class GetAccessAddressAckActor extends BaseUntypedActor {

    private ChannelHandlerContext ctx;
    private NavigateResponse response;

    public GetAccessAddressAckActor(ChannelHandlerContext ctx, NavigateResponse response) {
        this.ctx = ctx;
        this.response = response;
    }

    @Override
    public void onMsgReceive(Object msg) {
        try {
            if (msg instanceof GetAccessAddressOutput) {
                GetAccessAddressOutput output = (GetAccessAddressOutput) msg;
                this.response.setAccessAddressList(this.getAccessAddressList(output));
                this.response.setFileServer(this.getFileServer());
                ApiResponseHelper.sendApiResponse(this.ctx, Result.ok(this.response));
                return;
            }

            ApiResponseHelper.sendApiResponse(this.ctx, API_UNSUPPORTED_API_ACK_MESSAGE_TYPE);
        } catch (Exception ex) {
            log.error("ApiAckActor.onMsgReceive() error!", ex);
            ApiResponseHelper.sendApiResponse(this.ctx, SYSTEM_ERROR);
        }
    }

    /**
     * getFileServer
     * 导航的职责是下发接入地址和全局配置，这里文件服务Server先用本机地址作为演示用；
     */
    private String getFileServer() {
        int port = ConfigurationAllLoader.getInstance().getFileServerConfig().getHttpPort();
        return "http://127.0.0.1:" + port + "/";
    }

    /**
     * getAccessAddressList
     * 先只支持TCP接入地址下发，目前只是从数据结构上支持多地址下发；
     */
    private List<AccessServerAddress> getAccessAddressList(GetAccessAddressOutput output) {
        List<AccessServerAddress> serverAddressList = new ArrayList<>();
        AccessServerAddress tcpServerAddress = AccessServerAddress.builder()
                .address(output.getAccessAddress())
                .protocol(ConnectType.TCP.getCode())
                .build();
        serverAddressList.add(tcpServerAddress);

        return serverAddressList;
    }
}
